package myzzyl.handler;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.context.SaTokenContext;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import myzzyl.domain.pojo.JwtUser;
import myzzyl.domain.pojo.SysUser;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Date;

@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("开始插入填充...");
        Long userId = 1L; // 默认用户id
        try {
            // 获取会话缓存
            JwtUser user = (JwtUser) StpUtil.getSession().get("jwtUser");
            if (ObjectUtil.isEmpty(user)) {
                userId = user.getId();
            }
        } catch (Exception e) {
            log.warn(e.getMessage() + "无法获取登录用户id，使用默认用户ID: {}", userId);
        }
        this.strictInsertFill(metaObject, "createBy", Long.class, userId);
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "updateBy", Long.class, userId);
        this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("开始更新填充...");
        Long userId = 1L; // 默认用户id
        try {
            // 获取会话缓存
            JwtUser user = (JwtUser) StpUtil.getSession().get("jwtUser");
            if (ObjectUtil.isEmpty(user)) {
                userId = user.getId();
            }
        } catch (Exception e) {
            log.warn(e.getMessage() + "无法获取登录用户id，使用默认用户ID: {}", userId);
        }
        this.strictUpdateFill(metaObject, "updateBy", Long.class, userId);
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
    }

}
